package dev.werillib.camera

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import androidx.fragment.app.Fragment
import dev.werillib.android.PermissionUtil
import dev.werillib.android.ToastUtil
import dev.werillib.utils.*
import top.zibin.luban.OnCompressListener
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

open class TakePhotoFragment : Fragment(), TakePhoto, TakePhotoResultListener {
    override fun takeSuccess(file: File) {

    }

    override fun takeFail() {

    }

    lateinit var takePhoto: TakePhoto
    private lateinit var takePhotoResultListener: TakePhotoResultListener
    private var photoPath: String? = null
    private var compress = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        takePhoto = this
        takePhotoResultListener = this
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                TakePhotoConstant.REQUEST_CODE_FROM_GALLERY -> {
                    if (data != null && data.data != null) {
                        val proj = arrayOf(MediaStore.Images.Media.DATA)
                        val cursor = activity?.contentResolver?.query(data.data!!, proj, null, null, null)
                        if (cursor != null && cursor.moveToFirst()) {
                            val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                            photoPath = cursor.getString(columnIndex)
                            if (photoPath == null) {
                                photoPath = FileUtil.getFilePathByUri(context!!, data.data!!)
                            }
                            cursor.close()
                        } else {
                            photoPath = data.data!!.path
                        }

                        if (FileUtil.exists(photoPath)) {
                            setBack(File(photoPath), compress)
                        } else {
                            takePhotoResultListener.takeFail()
                        }
                    }
                }

                TakePhotoConstant.REQUEST_CODE_FROM_CAPTURE -> {
                    if (data != null) {
                        var imagePhoto: Bitmap? = null
                        if (data.data != null || data.extras != null) { //防止没有返回结果
                            val uri = data.data
                            if (uri != null) {
                                imagePhoto = BitmapFactory.decodeFile(uri.path) //拿到图片
                            }
                            if (imagePhoto == null) {
                                val bundlePic = data.extras
                                if (bundlePic != null) {
                                    imagePhoto = bundlePic.get("data") as Bitmap
                                } else {
                                    takePhotoResultListener.takeFail()
                                }
                            }
                        } else {
                            d("get picture fail")
                            takePhotoResultListener.takeFail()
                        }
                        if (imagePhoto != null) {
                            photoPath = FileUtil.getLocalPath() + "temp_" +
                                SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
                                    .format(Date()) + ".jpg"
                            BitmapUtil.saveImage(imagePhoto, photoPath!!)
                            imagePhoto.recycle()
                            setBack(File(photoPath), compress)
                        }
                    }
                }
            }
        }

    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            when (requestCode) {
                TakePhotoConstant.REQUEST_CODE_FROM_GALLERY -> onPickFromGallery(compress)
                TakePhotoConstant.REQUEST_CODE_FROM_CAPTURE -> onPickFromCapture(compress)
            }
        }
    }

    override fun onPickFromCapture(compress: Boolean) {
        this.compress = compress
        if (!PermissionUtil.checkSelfPermission(context!!, TakePhotoConstant.TAKEPHOTO_PERMISSIONS)) {
            PermissionUtil.requestPermission(
                activity!!,
                TakePhotoConstant.TAKEPHOTO_PERMISSIONS,
                TakePhotoConstant.REQUEST_CODE_FROM_CAPTURE
            )
        } else {
            val state = Environment.getExternalStorageState()
            if (state == Environment.MEDIA_MOUNTED) {
                val getImageByCamera = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                startActivityForResult(getImageByCamera, TakePhotoConstant.REQUEST_CODE_FROM_CAPTURE)
            } else {
                ToastUtil.toast(context!!, "请插入SD卡！")
            }
        }
    }

    override fun onPickFromGallery(compress: Boolean) {
        this.compress = compress
        if (!PermissionUtil.checkSelfPermission(context!!, TakePhotoConstant.TAKEPHOTO_PERMISSIONS)) {
            PermissionUtil.requestPermission(
                activity!!,
                TakePhotoConstant.TAKEPHOTO_PERMISSIONS,
                TakePhotoConstant.REQUEST_CODE_FROM_GALLERY
            )
        } else {
            val innerIntent = Intent()
            innerIntent.action = Intent.ACTION_PICK
            innerIntent.type = "image/*"
            val wrapperIntent = Intent.createChooser(innerIntent, "相册")
            startActivityForResult(wrapperIntent, TakePhotoConstant.REQUEST_CODE_FROM_GALLERY)
        }
    }

    private fun setBack(file: File, compress: Boolean) {
        when (compress) {
            true -> {
                Compress.compressImage(context!!, file, object : OnCompressListener {
                    override fun onStart() {}

                    override fun onSuccess(file: File) {
                        takePhotoResultListener.takeSuccess(file)
                    }

                    override fun onError(e: Throwable) {
                        takePhotoResultListener.takeFail()
                    }
                })
            }
            false -> {
                takePhotoResultListener.takeSuccess(file)
            }
        }
    }
}